<template>
  <div class='flex gap-3'>
    <div class='flex-1'>
      <div class='flex flex-col gap-3'>
        <div class='bg-white rounded p-3'>
          <div class='mb-2'>
            <el-button
              v-for='item in list'
              :type="item.isActive ? 'primary' : 'default'"
              :key='item.id'
              @click='!item.needLogin?clickHandle(item):()=>{}'
              v-login='!!item.needLogin?()=>clickHandle(item):undefined'
            >{{ item.name }}
            </el-button>
          </div>
          <div class='bg-gray-100 p-3.5 my-1 rounded' v-nologin-show>
            点击
            <el-button type='primary' link v-login='() => {}'>登录</el-button>
            ,快来和大家讨论吧~
          </div>
          <div class='task_input' v-login-show>
            <MyTextarea v-model='ordinaryPost'>
              <el-button type='primary' round @click='handleAddTask' style='padding: 0 30px'
              >发布
              </el-button
              >
            </MyTextarea>
          </div>
        </div>
        <div class='p-3 bg-white rounded'>
          <el-tabs v-model='activeName'>
            <el-tab-pane
              v-for='item in panelList'
              :label='item.name'
              :key='item.name'
              :name='item.id'
            >
              <ArticleList
                :list='taskList!'
                :pagination='taskPagination'
                @refresh='handleRefresh'
              ></ArticleList>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <div class='w-80 flex flex-col gap-3'>
      <GoLogin />
      <HotArticle />
    </div>
  </div>
</template>


<script setup lang='ts'>
import { TaskEntity } from '~/composables/api/task'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import MyTextarea from '@/components/MyTextarea/index.vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useWsLoginStore } from '@/stores/ws'


const router = useRouter()
const userStore = useUserStore()
const loginStore = useWsLoginStore()

const userId = computed(() => userStore.userInfo?.uid || '1000000')

// const activeMenu = inject('activeMenu', ref('-1'))


const list = ref<{ name: string; id: number; isActive?: boolean; path?: string, needLogin?: boolean }[]>([
  {
    name: '随便聊',
    id: -1,
    isActive: true,
  },
  {
    name: '发任务',
    id: -2,
    isActive: false,
    path: '/main/task/handle',
    needLogin: true,
  },
  {
    name: '找任务',
    id: 1,
    path: `/main/typePostList/1`,
    isActive: false,
  },
  {
    name: '找帮忙',
    id: 2,
    path: '/main/typePostList/2',
    isActive: false,
  },
])

const clickHandle = (item: any) => {
  list.value.forEach((item: any) => {
    item.isActive = false
  })
  item.isActive = true
  if (item.path) {
    // 判断是否是发任务按钮
    if (item.id === -2) {
      // 在路由跳转时添加type参数
      router.push({
        path: item.path,
        query: {
          isHome: 1
        }
      });
    } else {
      router.push(item.path);
    }
  }
}

const panelList = ref([
  {
    name: '自己',
    id: 3,
    needLogin: true,
  },
  {
    name: '最新',
    id: -1,
  },
  {
    name: '图片',
    id: 8,
  },
  {
    name: '视频',
    id: 9,
  },
])


const activeName = ref(-1)

const taskList = ref<TaskEntity[]>()

const taskPagination = ref<any>({
  pageSize: 10,
  pageNum: 1,
  total: 0,
})

// 监听标签切换
watch(activeName, async (newVal) => {
  // 当tab切换，分页的num重置成1
  taskPagination.value.pageNum = 1
  const queryData = {
    type: newVal > 0 ? newVal : 3,
    userId: undefined
  }
  // 没登录先登录
  if (!userStore.isSign) {
    loginStore.showLogin = true
    return
  }
  // 只有自己tab传userId
  if (newVal === 3) {
    queryData.userId = localStorage.getItem('userId')
    await getTaskList(queryData)
  } else if (newVal === -2) {
    await getTaskList(queryData)
  } else {
    await getTaskList(queryData)
  }

})

const getTaskList = async (params?: object) => {
  const queryData = {
    ...params,
    pageSize: taskPagination.value.pageSize,
    pageNum: taskPagination.value.pageNum,
  }
  const data = (await service.task.list(queryData)) || {}
  taskList.value = data.list
  taskPagination.value.total = data.total
}

onMounted(async () => {
  const queryData = {
    type: activeName.value > 0 ? activeName.value : 3,
    userId: undefined,
  }
  if (activeName.value == -1) {
    queryData.type = 3
  }
  await getTaskList(queryData)
})

const handleRefresh = (pagination?: any) => {
  if (pagination) {
    taskPagination.value.pageSize = pagination.pageSize
    taskPagination.value.pageNum = pagination.pageNum
  }
  // 点击页码的时候传当前type和userId,加判断，只有自己列表传userId
  const queryData = {
    type: activeName.value > 0 ? activeName.value : 3,
    userId: activeName.value === 3 ? (userId.value > 0 ? userId.value : undefined) : undefined,
  }
  getTaskList(queryData)
}

const ordinaryPost = ref({
  content: '',
  images: [],
})

const location = localStorage.getItem('location') ? JSON.parse(localStorage.getItem('location') as string) : {
  longitude: -1,
  latitude: -1,
}

// 首页随便聊tab的发布按钮
const handleAddTask = async () => {
  const data = {
    type: 0,
    description: ordinaryPost.value.content,
    images: ordinaryPost.value.images,
    x: location.longitude || 120.58,
    y: location.latitude || 31.29,
  }
  if (data.description.trim() !== '') {
    await service.task.add(data)
    const queryData = {
      type: activeName.value > 0 ? activeName.value : 3,
      userId: userId.value > 0 ? userId.value : undefined,
    }
    getTaskList(queryData)
    // 清空images
    ordinaryPost.value.images = []
    ordinaryPost.value.content = ''
  } else {
    ElMessage.warning('输入内容不为空~')
  }
}
</script>

